package org.icy.core.setup.manipulate;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.icy.core.Application;
import org.icy.utils.PathUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ConfigManipulate {

	private Map<String, String> map;

	public ConfigManipulate(Map<String, String> map) {
		this.map = map;
	}
	
	public void manipulate(boolean reload) throws ParserConfigurationException, SAXException,
			IOException, TransformerException {
		String path = PathUtils.getAbsolutePath("/ice.xml");
		// parse the XML file
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(path);
		NodeList list = doc.getElementsByTagName("param");
		for (int i = 0; i < list.getLength(); i++) {
			Element element = (Element) list.item(i);
			String name = element.getAttribute("name");
			if (map.containsKey(name)) {
				element.setAttribute("value", map.get(name));
			}
		}
		
		// save the XML file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		Node node = doc.getDocumentElement();
		Source src = new DOMSource(node);
		Result dest = new StreamResult(new File(path));
		transformer.transform(src, dest);
		
		if (reload)
			Application.getInstance().reloadConfiguration();
	}
}
